package com.ck.express.activity

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.ck.express.R
import com.ck.express.databinding.ActivityLoginBinding
import com.ck.express.models.GridRequest
import com.ck.express.models.LoginRequest
import com.ck.express.tcp.TcpClient
import com.ck.express.tcp.TcpOperationDownClient
import com.ck.express.tcp.TcpOperationGirdClient
import com.ck.express.utils.JsonUtil
import com.ck.express.utils.JsonUtil.objectMapper
import com.ck.express.utils.MockDeviceInfoProvider
import com.ck.express.utils.TimeUtil
import com.ck.express.vo.ApiResponse
import com.ck.express.vo.GridVO
import com.ck.express.vo.LoginVO
import com.fasterxml.jackson.core.type.TypeReference
import com.google.android.material.card.MaterialCardView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString

// 登录界面 - LoginActivity.kt (优化)
class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var prefs: SharedPreferences
    private val loadingDialog by lazy { createLoadingDialog() }


    companion object {
        const val KEY_LOGIN_IP = "login_ip"
        const val KEY_LOGIN_PORT = "login_port"
        const val KEY_UNLOAD_IP = "unload_ip"
        const val KEY_UNLOAD_PORT = "unload_port"
        const val KEY_SORT_IP = "sort_ip"
        const val KEY_SORT_PORT = "sort_port"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 初始化SharedPreferences
        prefs = getSharedPreferences("ip_config", Context.MODE_PRIVATE)

        // 设置蓝色主题
        window.statusBarColor = ContextCompat.getColor(this, R.color.primary_dark)

        binding.loginButton.apply {
            setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.primary))
            setTextColor(Color.WHITE)
            setOnClickListener { attemptLogin() }
        }

        // 设置系统设置按钮点击事件
        binding.settingsButton.setOnClickListener {
            showIpConfigDialog()
        }
    }

    private fun showIpConfigDialog() {
        val padding = 32
        val layout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(padding, padding, padding, padding)
        }

        layout.addView(createSectionCard("登录服务器配置",
            createIpEditText("IP", prefs.getString(KEY_LOGIN_IP, "")),
            createPortEditText("端口", prefs.getString(KEY_LOGIN_PORT, ""))
        ))

        layout.addView(createSectionCard("下车服务器配置",
            createIpEditText("IP", prefs.getString(KEY_UNLOAD_IP, "")),
            createPortEditText("端口", prefs.getString(KEY_UNLOAD_PORT, ""))
        ))

        layout.addView(createSectionCard("落格服务器配置",
            createIpEditText("IP", prefs.getString(KEY_SORT_IP, "")),
            createPortEditText("端口", prefs.getString(KEY_SORT_PORT, ""))
        ))

        val scrollView = ScrollView(this).apply {
            addView(layout)
        }

        AlertDialog.Builder(this)
            .setTitle("服务器配置")
            .setView(scrollView)
            .setPositiveButton("保存") { _, _ ->
                // 保存逻辑（根据顺序获取文本）
                val editTexts = layout.findViewsWithType<EditText>(EditText::class.java)
                prefs.edit().apply {
                    putString(KEY_LOGIN_IP, editTexts[0].text.toString())
                    putString(KEY_LOGIN_PORT, editTexts[1].text.toString())
                    putString(KEY_UNLOAD_IP, editTexts[2].text.toString())
                    putString(KEY_UNLOAD_PORT, editTexts[3].text.toString())
                    putString(KEY_SORT_IP, editTexts[4].text.toString())
                    putString(KEY_SORT_PORT, editTexts[5].text.toString())
                    apply()
                }
                TcpClient.configure(
                    editTexts[0].text.toString(),
                    editTexts[1].text.toString().toIntOrNull() ?: 10001
                )
                TcpOperationDownClient.configure(
                    editTexts[2].text.toString(),
                    editTexts[3].text.toString().toIntOrNull() ?: 10004
                )
                TcpOperationGirdClient.configure(
                    editTexts[4].text.toString(),
                    editTexts[5].text.toString().toIntOrNull() ?: 10003
                )
                Toast.makeText(this, "配置已保存", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun createSectionCard(title: String, vararg views: EditText): MaterialCardView {
        val sectionLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(24, 16, 24, 16)
        }

        val titleView = TextView(this).apply {
            text = title
            textSize = 16f
            setTypeface(null, Typeface.BOLD)
            setTextColor(ContextCompat.getColor(this@LoginActivity, R.color.primary_dark))
        }

        sectionLayout.addView(titleView)
        views.forEach { sectionLayout.addView(it) }

        return MaterialCardView(this).apply {
            radius = 16f
            cardElevation = 6f
            setCardBackgroundColor(Color.WHITE)
            useCompatPadding = true
            val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                topMargin = 16
            }
            layoutParams = params
            addView(sectionLayout)
        }
    }

    fun <T> ViewGroup.findViewsWithType(clazz: Class<T>): List<T> {
        val result = mutableListOf<T>()
        for (i in 0 until childCount) {
            val child = getChildAt(i)
            if (clazz.isInstance(child)) {
                result.add(clazz.cast(child)!!)
            }
            if (child is ViewGroup) {
                result.addAll(child.findViewsWithType(clazz))
            }
        }
        return result
    }





    /*private fun showIpConfigDialog() {
        val layout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(32, 16, 32, 16)
        }

        // 登录服务器配置
        val loginIpEditText = createIpEditText("登录服务器IP", prefs.getString(KEY_LOGIN_IP, ""))
        val loginPortEditText = createPortEditText("登录服务器端口", prefs.getString(KEY_LOGIN_PORT, ""))

        // 下车服务器配置
        val unloadIpEditText = createIpEditText("下车服务器IP", prefs.getString(KEY_UNLOAD_IP, ""))
        val unloadPortEditText = createPortEditText("下车服务器端口", prefs.getString(KEY_UNLOAD_PORT, ""))

        // 落格服务器配置
        val sortIpEditText = createIpEditText("落格服务器IP", prefs.getString(KEY_SORT_IP, ""))
        val sortPortEditText = createPortEditText("落格服务器端口", prefs.getString(KEY_SORT_PORT, ""))

        addSection(layout, "登录服务器配置")
        layout.addView(loginIpEditText)
        layout.addView(loginPortEditText)

        addSection(layout, "下车服务器配置")
        layout.addView(unloadIpEditText)
        layout.addView(unloadPortEditText)

        addSection(layout, "落格服务器配置")
        layout.addView(sortIpEditText)
        layout.addView(sortPortEditText)

        AlertDialog.Builder(this)
            .setTitle("服务器配置")
            .setView(layout)
            .setPositiveButton("保存") { _, _ ->
                prefs.edit().apply {
                    putString(KEY_LOGIN_IP, loginIpEditText.text.toString())
                    putString(KEY_LOGIN_PORT, loginPortEditText.text.toString())
                    putString(KEY_UNLOAD_IP, unloadIpEditText.text.toString())
                    putString(KEY_UNLOAD_PORT, unloadPortEditText.text.toString())
                    putString(KEY_SORT_IP, sortIpEditText.text.toString())
                    putString(KEY_SORT_PORT, sortPortEditText.text.toString())
                    apply()
                }
                TcpClient.configure(
                    loginIpEditText.text.toString(),
                    loginPortEditText.text.toString().toIntOrNull() ?: 10001
                )
                Toast.makeText(this, "配置已保存", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("取消", null)
            .show()
    }*/

    private fun createIpEditText(hint: String, defaultValue: String?): EditText {
        return EditText(this).apply {
            this.hint = hint
            setText(defaultValue)
            inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                bottomMargin = 16
            }
        }
    }

    private fun createPortEditText(hint: String, defaultValue: String?): EditText {
        return EditText(this).apply {
            this.hint = hint
            setText(defaultValue)
            inputType = InputType.TYPE_CLASS_NUMBER
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                bottomMargin = 16
            }
        }
    }

    private fun addSection(layout: LinearLayout, title: String) {
        val textView = TextView(this).apply {
            text = title
            textSize = 16f
            setTextColor(ContextCompat.getColor(this@LoginActivity, R.color.primary_dark))
            setTypeface(null, Typeface.BOLD)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                topMargin = 24
                bottomMargin = 8
            }
        }
        layout.addView(textView)
    }

    private fun attemptLogin() {
        val username = binding.usernameEditText.text.toString()
        val password = binding.passwordEditText.text.toString()

        if (username.isBlank() || password.isBlank()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        // 显示加载对话框
        loadingDialog.show()

        // 创建登录请求对象
        val loginRequest = LoginRequest(
            clientMac = MockDeviceInfoProvider.getMockMacAddress(),
            clientIp = MockDeviceInfoProvider.getMockIpAddress(),
            userCode = username,
            password = password
        )
        val jsonBody = JsonUtil.json.encodeToString(loginRequest)

        // 发送登录请求
        CoroutineScope(Dispatchers.IO).launch {
            try {
               /* val responseJson = "{\n" +
                        "  \"code\": \"000\",\n" +
                        "  \"msg\": \"登录成功\",\n" +
                        "  \"data\": {\n" +
                        "    \"txId\": \"abc123xyz\",\n" +
                        "    \"serverTime\": \"2025-06-14 12:34:56.789\",\n" +
                        "    \"userCode\": \"user_001\",\n" +
                        "    \"userName\": \"张三\",\n" +
                        "    \"userId\": \"ding1234567890\",\n" +
                        "    \"orgCode\": \"ORG001\",\n" +
                        "    \"orgName\": \"圆通速递\",\n" +
                        "    \"orgType\": \"分公司\",\n" +
                        "    \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\",\n" +
                        "    \"signature\": \"abcd1234efgh5678\",\n" +
                        "    \"extend1\": \"扩展字段1\",\n" +
                        "    \"extend2\": \"扩展字段2\",\n" +
                        "    \"extend3\": \"扩展字段3\"\n" +
                        "  }\n" +
                        "}\n" ;*/
                val responseJson = TcpClient.send(jsonBody)
                Log.i("登录返回", "${responseJson}")
                val response: ApiResponse<LoginVO> = objectMapper.readValue(responseJson,
                    object : TypeReference<ApiResponse<LoginVO>>() {})
                Log.i("登录返回解析", "${response}")
                withContext(Dispatchers.Main) {
                    loadingDialog.dismiss()
                    handleLoginResponse(response)
                }
            } catch (e: Exception) {
                Log.e("LoginActivity", "登录失败：${e}")
                withContext(Dispatchers.Main) {
                    loadingDialog.dismiss()
                    Toast.makeText(
                        this@LoginActivity,
                        "登录失败: ${e.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
    }

    private fun handleLoginResponse(response: ApiResponse<LoginVO>) {
        when (response.code) {
            "000" -> { // 成功
                response.data?.let { data ->
                    // 保存用户信息
                    LogisticsApp.userSession.saveUserInfo(data)


                    // 跳转到主菜单
                    startActivity(Intent(this, MenuActivity::class.java))
                    // 获取格口方案
                    fetchGridPlan()

                    finish()
                } ?: run {
                    Toast.makeText(this, "登录成功但返回数据为空", Toast.LENGTH_SHORT).show()
                }
            }

            "015" -> Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_LONG).show()
            "020" -> Toast.makeText(this, "用户不属于本网点", Toast.LENGTH_LONG).show()
            "419" -> Toast.makeText(this, "用户名不存在", Toast.LENGTH_LONG).show()
            else -> Toast.makeText(
                this,
                "登录失败 (${response.code}): ${response.msg ?: "系统异常"}",
                Toast.LENGTH_LONG
            ).show()
        }
    }

    private fun fetchGridPlan() {
        val tag = "GridPlanFetcher"
        lifecycleScope.launch {
            runCatching {
                val request = GridRequest(
                    mty = "8600",
                    signature = LogisticsApp.userSession.getAuthToken(),
                    createTime = TimeUtil.getCurrentTimestamp()
                )
                val requestData = JsonUtil.json.encodeToString(request)
                Log.i("LoginActivity","发送请求：${requestData}")
                val json = withContext(Dispatchers.IO) {
                    TcpClient.send(requestData)
                }

                JsonUtil.json.decodeFromString<ApiResponse<GridVO>>(json)
            }.onSuccess { response ->
                Log.i(tag,"格口方案返回:${response}")
                if (response.code == "000" && response.data != null) {
                    val schemeId = response.data.schemeId
                    LogisticsApp.userSession.saveGridSchemeId(schemeId)
                    Log.d(tag, "格口方案获取成功，ID: $schemeId")
                } else {
                    Log.e(tag, "格口方案获取失败：${response.msg}")
                }
            }.onFailure { e ->
                Log.e(tag, "格口方案请求异常", e)
            }
        }
    }


    private fun createLoadingDialog(): Dialog {
        val dialog = Dialog(this, R.style.CustomProgressDialog).apply {
            setContentView(R.layout.dialog_loading)
            setCancelable(false)

            window?.apply {
                setBackgroundDrawableResource(android.R.color.transparent)
                setLayout(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
            }

            // 设置进度条颜色
            findViewById<ProgressBar>(R.id.progressBar)?.apply {
                indeterminateDrawable?.setColorFilter(
                    ContextCompat.getColor(context, R.color.primary),
                    PorterDuff.Mode.SRC_IN
                )
            }

            // 设置加载文字
            findViewById<TextView>(R.id.tvLoading)?.apply {
                setTextColor(ContextCompat.getColor(context, R.color.primary_dark))
            }
        }
        return dialog
    }


}